package cn.yuhh.controller;

import cn.yuhh.entity.Tag;
import cn.yuhh.serviec.ITagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;

@Configuration
@RequestMapping("/admin")
public class TagController {

    @Autowired
    private ITagService tagService;

    @GetMapping("/tags")
    public String tags(@PageableDefault(size = 10,sort = {"id"},direction= Sort.Direction.DESC) Pageable pageable,
                       Model model) {
        model.addAttribute("tags", tagService.listTag(pageable));
        return "admin/tags";
    }

    @GetMapping("/tags/{id}/edit")
    public String editTag(@PathVariable Long id, Model model) {
        model.addAttribute("tag", tagService.findById(id));
        return "admin/tags-input";
    }

    @GetMapping("/tags/{id}/delete")
    public String deleteTag(@PathVariable Long id,RedirectAttributes attributes) {
        tagService.deleteById(id);
        attributes.addFlashAttribute("message", "删除成功!");
        return "redirect:/admin/tags";
    }

    @GetMapping("/tags/input")
    public String inputTag(Model model) {
        model.addAttribute("tag", new Tag());
        return "admin/tags-input";
    }

    @PostMapping("/tags/{id}")
    public String inputTags(@PathVariable Long id, Tag tag, RedirectAttributes attributes) {
        Tag tag1=tagService.findByName(tag.getName());
        if (tag1 != null) {
            attributes.addFlashAttribute("message", "已有同名的类别，请重新修改");
        } else {
            tagService.updateTagById(id, tag);
            attributes.addFlashAttribute("message", "修改成功！");
        }
        return "redirect:/admin/tags";
    }

    @PostMapping("/tags")
    public String inputTags(@Valid Tag tag, RedirectAttributes attributes) {
        Tag tag1=tagService.findByName(tag.getName());
        if (tag1 != null) {
            attributes.addFlashAttribute("message", "已有同名的类别，请重新修改");
        } else {
            Tag t=tagService.save(tag);
            if (t != null) {
                attributes.addFlashAttribute("message", "保存成功！");
            } else {
                attributes.addFlashAttribute("message", "保存失败!");
            }
        }
        return "redirect:/admin/tags";
    }


}
